package common;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import table.User;

/**
 * 操作Excel的工具类
 */
public class ExcelTools {
    
	/**
	 * 从指定格式的Excel文件中读取用户信息
	 * @param file Excel的路径
	 * @return 用户列表
	 */
    public static List<User> readUsersFromExcel(File file) {
    	List<User> list = new ArrayList<>();
    	try {
    		InputStream is = new FileInputStream(file.getAbsolutePath());
    		Workbook wb = Workbook.getWorkbook(is);
    		Sheet sheet = wb.getSheet(0);
    		int r = 0;
    		while(true) {
    			r++;
    			User u = new User();
    			String uid 		= sheet.getCell(0, r).getContents().trim();
    			String uname 	= sheet.getCell(1, r).getContents().trim();
    			String pw 		= sheet.getCell(2, r).getContents().trim();
    			String tid 		= sheet.getCell(3, r).getContents().trim();
    			if(uid.isEmpty() && uname.isEmpty()) break;
    			if(uid.isEmpty() || uname.isEmpty()) continue;
    			u.setId(uid);
    			u.setName(uname);
    			int teamid = 0;
    			try { teamid = Integer.parseInt(tid); } catch (Exception e) {}
    			u.setTeamid(teamid);
    			if(pw.isEmpty()) {
    				u.setPassword("000000");
    			} else {
    				u.setPassword(pw);
    			}
    			u.setGroup("user");
    			list.add(u);
    		}
    		
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    	return list;
    }
}